package com.neusoft.neuiotms.dcam.fixed.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetTypeDTO;
import com.neusoft.neuiotms.dcam.fixed.model.AssetType;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetTypeRepository;

@Component
public class AssetTypeConverter extends AbstractConverter<AssetType, AssetTypeDTO> {

    @Autowired
    private AssetTypeRepository assetTypeRepository;

    @Override
    public AssetType toModel(final AssetTypeDTO dto) {
        AssetType model;
        if (dto.isNew()) {
            model = new AssetType();
        } else {
            model = this.assetTypeRepository.getOne(dto.getId());
        }
        model.setCode(dto.getCode());
        model.setName(dto.getName());
        model.setSort(dto.getSort());
        model.setMeasureUnit(dto.getMeasureUnit());
        if ((dto.getParentId() != null) && (dto.getParentId() != -1)) {
            model.setParent(this.assetTypeRepository.getOne(dto.getParentId()));
        }
        if (dto.getParentCode() != null) {
            model.setParent(this.assetTypeRepository.findByCode(dto.getParentCode()));
        }
        return model;
    }

    @Override
    public AssetTypeDTO toDTO(final AssetType model, final boolean forListView) {
        final AssetTypeDTO dto = new AssetTypeDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        dto.setSort(model.getSort());
        dto.setMeasureUnit(model.getMeasureUnit());
        if (model.getParent() != null) {
            dto.setParentId(model.getParent().getId());
            dto.setParentName(model.getParent().getName());
            dto.setParentCode(model.getParent().getCode());
        }
        return dto;
    }

}
